﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
using System.Threading;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.WindowsAPICodePack.Dialogs;
using Microsoft.WindowsAPICodePack.Shell;


namespace ChannelJsonConvet
{
    /// <summary>
    /// PackInfoWnd.xaml 的交互逻辑
    /// </summary>
    public partial class PackInfoWnd : Window
    {
        public PackInfoData m_data = null;

        public string m_apkDir;

        public string m_selectApkPath;

        string m_channelName;

        public PackInfoWnd(string channelName,string apkDir)
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            m_data = new PackInfoData();
            m_apkDir = apkDir;

            InitializeComponent();
            m_channelName = channelName;
            label_ChannelName.Content = m_channelName;
        }

        public PackInfoWnd(PackInfoData data,string channelName,string apkDir)
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            m_data = data;
            m_apkDir = apkDir;

            InitializeComponent();

            m_channelName = channelName;
            label_ChannelName.Content = m_channelName;
            textBox_version.Text = m_data.version_name;
            string[] dirArray = m_data.install_package_url.Split('/');
            textBox_apkSelect.Text = dirArray[dirArray.Length - 1];
            textBox_apkSize.Text = m_data.install_package_size;
            textBox_apkMd5.Text = m_data.install_package_md5;
            textBox_apkDir.Text = m_data.install_package_url;

        }

        private void button_ApkSelect_Click(object sender, RoutedEventArgs e)
        {
            ShellContainer selectedFolder = null;
            selectedFolder = KnownFolders.Computer as ShellContainer;
            CommonOpenFileDialog dialog = new CommonOpenFileDialog();
            dialog.InitialDirectory = m_apkDir;
            dialog.IsFolderPicker = false;//设置为选择文件夹
            dialog.InitialDirectoryShellContainer = selectedFolder;
            dialog.EnsureReadOnly = true;

            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                if(!File.Exists(dialog.FileName))
                {
                    //Console.WriteLine("不存在所选文件，请重新选择");
                    MainWindow.ShowTipWnd(this, "提示", "不存在所选文件，请重新选择");
                    return;
                }

                m_selectApkPath = dialog.FileName;
                textBox_apkSelect.Text = m_selectApkPath;
                m_data.install_package_url ="/"+ m_channelName+"/"+ textBox_version.Text+"/"+ System.IO.Path.GetFileName(m_selectApkPath);
                textBox_apkDir.Text = m_data.install_package_url;
                //if (m_selectApkPath.Contains(m_apkDir))
                //{
                //    m_data.install_package_url = m_selectApkPath.Remove(0,m_apkDir.Length).Replace(@"\", "/");
                //    textBox_apkDir.Text = m_data.install_package_url;
                //}
                //else
                //{
                //    //Console.WriteLine("所选Apk不在设定的Apk目录中，无法计算相对路径，请自行填写");
                //    MainWindow.ShowTipWnd(this, "提示", "所选Apk不在设定的Apk目录中，无法计算相对路径，请自行填写");
                //}

                FileInfo fileInfo = new FileInfo(m_selectApkPath);
                m_data.install_package_size = fileInfo.Length.ToString();
                textBox_apkSize.Text = m_data.install_package_size;
                textBox_apkMd5.Text = "md5码计算中......";
                Task task = new Task((tb) => CalculateMd5(this.textBox_apkMd5), this.textBox_apkMd5);
                task.Start();
            }
        }

        void CalculateMd5(TextBox tb)
        {
            m_data.install_package_md5 = GetMD5HashFromFile(m_selectApkPath).ToUpper();
            Action<TextBox, string> updateAction = new Action<TextBox, string>(UpdateTb);
            tb.Dispatcher.BeginInvoke(updateAction, tb, m_data.install_package_md5);
        }

        void UpdateTb(TextBox tb, string text)
        {
            tb.Text = text;
        }

        

        private string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

        private void button_Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void button_Save_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            m_data.version_name = textBox_version.Text;
            m_data.install_package_size = textBox_apkSize.Text;
            m_data.install_package_md5 = textBox_apkMd5.Text;
            m_data.install_package_url = textBox_apkDir.Text;
        }

    }
}
